package me.tuyou.jdbc.po;

import lombok.Data;
import lombok.ToString;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description
 * @Author tuyou_cd
 * @Date 2020/6/2 14:23
 */
@Data
@ToString(exclude = {"applicationContext", "jdbcTemplate"})
@Component
@Scope("prototype")
public class User {

    @Resource
    private ApplicationContext applicationContext;

    /**
     * 不支持根据class直接反射生成po
     */
    @Resource
    private JdbcTemplate jdbcTemplate;

    private int id;
    private String name;
    private int age;

    public void createTableIfNotExists() {
        jdbcTemplate.update("create table if not exists user(id int auto_increment, name varchar(32), age int)");
    }

    public int save() {
        return jdbcTemplate.update("insert into user(name, age) values(?, ?)", name, age);
    }

    public List<User> queryAll() {
        return jdbcTemplate.query("select * from user", (rs, rowNum) -> {
            User bean = applicationContext.getBean(User.class);
            bean.setId(rs.getInt("id"));
            bean.setName(rs.getString("name"));
            bean.setAge(rs.getInt("age"));
            return bean;
        });

//        return Collections.singletonList(jdbcTemplate.queryForObject("select * from user limit 1", User.class));
    }
}
